package cn.emall.order.interceptor;

import cn.emall.cart.service.CartService;
import cn.emall.pojo.TbItem;
import cn.emall.pojo.TbUser;
import cn.emall.sso.service.TokenService;
import cn.emall.utils.CookieUtils;
import cn.emall.utils.EmallResult;
import cn.emall.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private TokenService tokenService;
    @Autowired
    private CartService cartService;
    @Value("${SSO_URL}")
    private String SSO_URL;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //从cookie中取token
        String token = CookieUtils.getCookieValue(request, "token");
        //如果token不存在,则用户是未登录状态,跳转到sso系统登录页面,登录成功后跳转带当前请求url
        if(StringUtils.isBlank(token)){
            response.sendRedirect(SSO_URL + "/page/login?redirect=" + request.getRequestURL());
            //拦截
            return false;
        }
        //如果token存在,则需要调用sso系统的服务,根据token获取用户信息
        EmallResult emallResult = tokenService.getUserByToken(token);
        //如果用户信息获取不到,则用户登录已经过期,需要重新登录
        if(emallResult.getStatus() != 200){
            //如果token不存在,则用户是未登录状态,跳转到sso系统登录页面,登录成功后跳转带当前请求url
            response.sendRedirect(SSO_URL + "/page/login?redirect=" + request.getRequestURL());
            //拦截
            return false;
        }
        //如果取到用户信息,则需要把用户信息写入request
        TbUser user = (TbUser) emallResult.getData();
        request.setAttribute("user",user);
        //判断cookie中是否含有购物车信息,如果有就合并到服务器
        String jsonCartList = CookieUtils.getCookieValue(request, "cart", true);
        if(StringUtils.isNotBlank(jsonCartList)){
            //合并购物车
            cartService.mergeCart(user.getId(), JsonUtils.jsonToList(jsonCartList, TbItem.class));
        }
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
